import React, { useState } from 'react';
import { Form, Input, Button, Card, Typography, App, Spin } from 'antd';
import { UserOutlined, LockOutlined, LoadingOutlined, CheckCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import axios from 'axios';
import { Link, useNavigate } from 'react-router-dom';

const { Title } = Typography;

const AdminLoginPage: React.FC = () => {
    const { message } = App.useApp();
    const navigate = useNavigate();
    const [loading, setLoading] = useState(false);
    const [statusMessage, setStatusMessage] = useState('');
    const [statusType, setStatusType] = useState<'loading' | 'success' | 'error'>('loading');

    const onFinish = async (values: any) => {
        setLoading(true);
        setStatusType('loading');
        setStatusMessage('正在验证管理员身份，请稍候...');

        try {
            const response = await axios.post('/api/auth/login/', values);
            const { token, is_staff } = response.data;

            if (token && is_staff === true) {
                localStorage.setItem('adminAuthToken', token);

                // 显示管理员登录成功状态
                setStatusType('success');
                setStatusMessage(`管理员登录成功！正在跳转到管理后台...`);

                // 存储管理员欢迎信息
                const adminWelcomeMsg = `欢迎进入管理后台，${values.username}！`;
                localStorage.setItem('adminWelcomeMessage', adminWelcomeMsg);
                console.log('AdminLoginPage: 存储管理员欢迎信息:', adminWelcomeMsg);

                // 延迟跳转到管理后台
                setTimeout(() => {
                    navigate('/admin/account');
                }, 1500);
            } else {
                setStatusType('error');
                setStatusMessage('登录失败，您不是管理员或凭据无效');
                message.error('登录失败，您不是管理员或凭据无效。');
                setTimeout(() => {
                    setStatusMessage('');
                }, 3000);
            }
        } catch (err: any) {
            const errorMsg = err.response?.data?.non_field_errors?.[0] || '登录失败，请检查您的凭据或联系系统管理员。';
            setStatusType('error');
            setStatusMessage(`管理员登录失败：${errorMsg}`);
            message.error(errorMsg);
            console.error('Admin login error:', err);
            setTimeout(() => {
                setStatusMessage('');
            }, 3000);
        } finally {
            setLoading(false);
        }
    };

    return (
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh', background: 'linear-gradient(to top left, #ffffff, #fff7e6)' }}>
            {/* 顶部状态提示组件 */}
            {statusMessage && (
                <div style={{
                    position: 'fixed',
                    top: '20px',
                    left: '50%',
                    transform: 'translateX(-50%)',
                    zIndex: 1000,
                    width: 'auto',
                    minWidth: '300px',
                    maxWidth: '500px'
                }}>
                    <Card
                        size="small"
                        style={{
                            background: 'rgba(255, 255, 255, 0.95)',
                            backdropFilter: 'blur(10px)',
                            border: `1px solid ${
                                statusType === 'success' ? '#52c41a' :
                                statusType === 'error' ? '#ff4d4f' : '#d9d9d9'
                            }`,
                            borderRadius: '8px',
                            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
                            textAlign: 'center'
                        }}
                    >
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '12px' }}>
                            {statusType === 'loading' && (
                                <Spin
                                    indicator={<LoadingOutlined style={{ fontSize: 16, color: '#1890ff' }} spin />}
                                />
                            )}
                            {statusType === 'success' && (
                                <CheckCircleOutlined style={{ fontSize: 16, color: '#52c41a' }} />
                            )}
                            {statusType === 'error' && (
                                <ExclamationCircleOutlined style={{ fontSize: 16, color: '#ff4d4f' }} />
                            )}
                            <span style={{
                                color: statusType === 'success' ? '#52c41a' :
                                       statusType === 'error' ? '#ff4d4f' : '#1890ff',
                                fontWeight: 500,
                                fontSize: '14px'
                            }}>
                                {statusMessage}
                            </span>
                        </div>
                    </Card>
                </div>
            )}

            <Card style={{ width: 400, boxShadow: '0 4px 8px 0 rgba(0,0,0,0.2)' }}>
                <div style={{ textAlign: 'center', marginBottom: '24px' }}>
                    <Title level={2}>管理员登录</Title>
                </div>
                <Form
                    name="admin_login"
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                    style={{ textAlign: 'center' }}
                >
                    <Form.Item
                        name="username"
                        rules={[{ required: true, message: '请输入管理员用户名!' }]}
                    >
                        <Input prefix={<UserOutlined />} placeholder="管理员用户名" size="large" />
                    </Form.Item>
                    <Form.Item
                        name="password"
                        rules={[{ required: true, message: '请输入密码!' }]}
                    >
                        <Input.Password prefix={<LockOutlined />} placeholder="密码" size="large" />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" style={{ width: '100%' }} size="large" loading={loading}>
                            登 录
                        </Button>
                    </Form.Item>
                     <Link to="/" className="admin-link">
                        返回用户登录
                    </Link>
                </Form>
            </Card>
        </div>
    );
};

export default AdminLoginPage;